﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Serialization;

namespace TFSUtils.Helpers
{
    class SerialiseHelper
    {
        private const string FILE_NAME = "data.txt";

        public static void SerialiseObject(object obj)
        {
            string fileName = obj.GetType().ToString() + FILE_NAME;

            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write, store))
            {
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(stream, obj);
            }
        }

        public static object DeserialiseObject<T>()
        {
            string fileName = typeof(T).ToString() + FILE_NAME;

            using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly())
            {
                if (store.FileExists(fileName))
                {
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Open, FileAccess.Read, store))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(T));
                        object obj = serializer.Deserialize(stream);
                        return obj;
                    }
                }
                else
                {
                    return null;
                }
            }
        }
    }
}
